<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Project;
use App\Models\RoleUser;
use App\Models\User;
use App\Services\RoleUserService;
use Illuminate\Http\Request;

class RoleUserController extends Controller
{

    protected $RoleUserService;
    public function __construct(RoleUserService $RoleUserService)
    {
        $this->RoleUserService = $RoleUserService;
    }

    public function index(Request $Request) {
        $data = RoleUser::with('role')->with('cert')->with('user')->where('project_id',$Request->project_id)->get();
        $project = Project::select('title','build_unit')->where('id',$Request->project_id)->first();
        return response()->json(['code' => '200', 'msg' => '操作成功','data' => $data,'project' => $project]);
    }

    public function roleUser(Request $Request) {
        $data = RoleUser::where('role_id',$Request->role_id)->where('project_id',$Request->project_id)->pluck('user_id');
        $user = User::whereIn('id',$data)->get();
        return response()->json(['code' => '200', 'msg' => '操作成功','data' => $user]);
    }

    public function show(Request $Request) {
        $data = RoleUser::find($Request->id);
        return response()->json(['code' => '200', 'msg' => '操作成功','data' => $data]);
    }

    /**
     * 存储一个新用户。
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  // parent_id 角色ID
     * @param  // name 角色名称
     * @param  // auth 权限
     * @param  // status 状态
     * @return \Illuminate\Http\Response
     */
    public function store(Request $Request)
    {
        $POSTONLY = RoleUser::POSTONLY;
        $input = $Request->only($POSTONLY);
        $data = $this->RoleUserService->insert($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data' => $data]);
    }


    public function update(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的用户']);
        }
        $POSTONLY = RoleUser::POSTONLY;
        $input = $Request->only($POSTONLY);
        $input['id'] = $Request->id;
        $data = $this->RoleUserService->update($input);
        return response()->json(['code' => '200', 'msg' => '操作成功','data' => $data]);
    }

    public function delete(Request $Request)
    {
        if(!$Request->id){
            return response()->json(['code' => '404', 'msg' => '请选择要操作的用户']);
        }
        $admin = RoleUser::find($Request->id);
        $admin->delete();
        return response()->json(['code' => '200', 'msg' => '操作成功']);
    }
}
